from dataclasses import dataclass, field
from datetime import datetime
from typing import List, Optional, Dict, Any


@dataclass
class AppInfo:
    """应用程序基本信息"""
    name: Optional[str] = None
    version: Optional[str] = None
    identifier: Optional[str] = None
    platform: Optional[str] = None
    size: Optional[int] = None
    min_os_version: Optional[str] = None
    install_path: Optional[str] = None
    last_modified: Optional[datetime] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'name': self.name,
            'version': self.version,
            'identifier': self.identifier,
            'platform': self.platform,
            'size': self.size,
            'min_os_version': self.min_os_version,
            'install_path': self.install_path,
            'last_modified': self.last_modified.isoformat() if self.last_modified else None
        }


@dataclass
class Framework:
    """应用程序使用的框架信息"""
    name: str
    confidence: float = 0.0
    version: Optional[str] = None
    category: str = "其他"
    is_main_framework: bool = False
    description: Optional[str] = None
    files: List[str] = field(default_factory=list)
    features: List[str] = field(default_factory=list)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'name': self.name,
            'confidence': self.confidence,
            'version': self.version,
            'category': self.category,
            'is_main_framework': self.is_main_framework,
            'description': self.description,
            'files': self.files,
            'features': self.features
        }


@dataclass
class AnalysisResult:
    """应用程序分析结果"""
    app_info: Optional[AppInfo] = None
    frameworks: List[Framework] = field(default_factory=list)
    analysis_date: datetime = field(default_factory=datetime.now)
    duration: float = 0.0
    errors: List[str] = field(default_factory=list)
    warnings: List[str] = field(default_factory=list)
    
    def add_framework(self, framework: Framework) -> None:
        """添加检测到的框架"""
        self.frameworks.append(framework)
    
    def add_error(self, error: str) -> None:
        """添加分析过程中的错误"""
        self.errors.append(error)
    
    def add_warning(self, warning: str) -> None:
        """添加分析过程中的警告"""
        self.warnings.append(warning)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'app_info': self.app_info.to_dict() if self.app_info else None,
            'frameworks': [f.to_dict() for f in self.frameworks],
            'analysis_date': self.analysis_date.isoformat(),
            'duration': self.duration,
            'errors': self.errors,
            'warnings': self.warnings
        }
    
    def get_main_frameworks(self) -> List[Framework]:
        """获取主要框架列表"""
        return [f for f in self.frameworks if f.is_main_framework]
    
    def get_frameworks_by_category(self, category: str) -> List[Framework]:
        """获取特定类别的框架列表"""
        return [f for f in self.frameworks if f.category == category]
    
    def get_framework_categories(self) -> List[str]:
        """获取所有框架类别列表"""
        return sorted(list(set(f.category for f in self.frameworks)))
    
    @property
    def summary(self) -> str:
        """生成分析结果摘要"""
        app_name = self.app_info.name if self.app_info else "未知应用"
        main_frameworks = self.get_main_frameworks()
        
        summary_text = f"应用: {app_name}\n"
        if self.app_info and self.app_info.version:
            summary_text += f"版本: {self.app_info.version}\n"
        
        summary_text += f"检测到 {len(self.frameworks)} 个框架\n"
        
        if main_frameworks:
            summary_text += "主要框架: " + ", ".join(f.name for f in main_frameworks) + "\n"
        
        for category in self.get_framework_categories():
            frameworks = self.get_frameworks_by_category(category)
            if frameworks:
                summary_text += f"{category}: " + ", ".join(f.name for f in frameworks) + "\n"
        
        if self.errors:
            summary_text += f"错误 ({len(self.errors)}): {self.errors[0]}" + ("..." if len(self.errors) > 1 else "") + "\n"
        
        return summary_text 
